//
//  SendLinesNameController.m
//  NtoccShipper
//
//  Created by 张天兴 on 2023/8/21.
//  Copyright © 2023 zhuchongjin. All rights reserved.
//

#import "SendLinesNameController.h"
#import "LineItemCodeCell.h"
#import "ObjectListIModel.h"
#import "ZTXNewObjectLinesController.h"
#import "SendLineController.h"
#import "LinesListController.h"
#import "SelectGoodsNameVC.h"

@interface SendLinesNameController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) CJTableView *tableView;
@property (nonatomic, assign) int page;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic,strong) NSString *refreshType; //刷新
@property (nonatomic, strong) UILabel *titLabel;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UITapGestureRecognizer *changeVoidceSet;
@property (nonatomic, strong) UIView *erwmView;
@property (nonatomic, strong) UIImageView *erwmImagView;
@property (nonatomic, strong) UIButton *buttonImag;
@property (nonatomic, strong) UIButton *comitterButton;

@end

@implementation SendLinesNameController


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self downRefresh];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitleName:CJLString(@"项目")];
    [self setBackLeftButton:@""];
    [self.tableView registerNib:[UINib nibWithNibName:@"LineItemCodeCell" bundle:nil] forCellReuseIdentifier:@"LineItemCodeCell"];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.comitterButton];
    WS(ws);
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
        [ws.tableView.mj_header beginRefreshing];
    }];
    [self initData];
}

- (void)initData{
    self.dataArr = [[NSMutableArray alloc]init];
    self.page = 1;
}

/// <#Description#>
- (void)loadData {
    
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderProject/list",CJBaseUrl);
    NSDictionary *dicPar = @{@"pageNum":CJStringWithFormat(@"%d",self.page),
                             @"pageSize":@"10",
                             @"projectName":@"",
                             @"isCancel":@""
    };
    //
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
        
        DLog(@"++++++++%@",responseObject);
        
        NSArray *list = responseObject[@"records"];
        NSString *total = CJStringWithFormat(@"%@",responseObject[@"total"]);
        if ([ws.refreshType isEqualToString:@"down"]) {
            [ws.dataArr removeAllObjects];
        }
        //
        NSError * error ;
        NSArray *arr = [ObjectListIModel arrayOfModelsFromDictionaries:list error:&error];
        [ws.dataArr addObjectsFromArray:arr];
        
        [ws.tableView.mj_header endRefreshing];
        [ws.tableView.mj_footer endRefreshing];
        
        if (ws.dataArr.count == total.intValue) {
            [ws.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        [ws.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        [ws.tableView.mj_header endRefreshing];
        [ws.tableView.mj_footer endRefreshingWithNoMoreData];
    }];
}

- (void)downRefresh{
    self.refreshType = @"down";
    self.page = 1;
    [self loadData];
}

- (void)upRefresh{
    self.refreshType = @"up";
    self.page ++;
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"LineItemCodeCell";
    LineItemCodeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.codeButton addTarget:self action:@selector(codeButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.deleteButton addTarget:self action:@selector(deleteButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.stopButton addTarget:self action:@selector(stopButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.xiugButton addTarget:self action:@selector(xiugButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    ObjectListIModel *model = self.dataArr[indexPath.row];
    [cell setCellInfoWithSourceModel:model];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LinesListController *sendVC = [[LinesListController alloc] init];
    ObjectListIModel *model = self.dataArr[indexPath.row];
    sendVC.projectCode = model.code;
    sendVC.strAddressCityName = model.shipperAddress;
    sendVC.strDownLoadCityCode = model.shipperSubdivisionCode;
    sendVC.strConsigneeLatitude = model.shipperLatitude;
    sendVC.strConsigneeLongitude = model.shipperLongitude;
    sendVC.shipperDetailAddress = model.shipperDetailAddress;
    sendVC.coalBigTypeName = model.coalBigTypeName;
    sendVC.coalBigType = model.coalBigType;
    sendVC.coalType = model.coalType;
    sendVC.coalTypeName = model.coalTypeName;
    [self pushVc:sendVC];
    
}
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(ws);
    UITableViewRowAction *moRenRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderProject/delete",CJBaseUrl);
        ObjectListIModel *model = self.dataArr[indexPath.row];
        NSDictionary *dicPar = @{@"codes":model.code,
        };
        [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:DeleteType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
            [ws.dataArr removeObjectAtIndex:indexPath.row];
            [ws.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]] withRowAnimation:UITableViewRowAnimationFade];
        } failure:^(NSError * _Nonnull error) {
            
        }];
       }];
    NSArray* arr = @[moRenRowAction];
    return arr;
}
- (void)codeButtonAction:(UIButton *)btn{
    CGPoint point = btn.center;//找到btn中心点记录下来
    point = [self.tableView convertPoint:point fromView:btn.superview];
    NSIndexPath* indexpath = [self.tableView indexPathForRowAtPoint:point];
    ObjectListIModel *model = self.dataArr[indexpath.row];
    self.titLabel.text = CJStringWithFormat(@"项目名称:%@",model.projectName);
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/wx/getProjectQrcode",CJBaseUrl);
    NSDictionary *dicPar = @{@"code":model.code,
                             @"isMobile":@"1"
    };
    //
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
        NSData* data = [[NSData alloc] initWithBase64EncodedString:responseObject options:0];
        ws.erwmImagView.image = [UIImage imageWithData:data];
        
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        
    }];
    
    [self.view addSubview:self.bgView];
}
- (void)deleteButtonAction:(UIButton *)btn{
    CGPoint point = btn.center;//找到btn中心点记录下来
    point = [self.tableView convertPoint:point fromView:btn.superview];
    NSIndexPath* indexpath = [self.tableView indexPathForRowAtPoint:point];
    ObjectListIModel *model = self.dataArr[indexpath.row];
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderProject/delete",CJBaseUrl);
    NSDictionary *dicPar = @{@"codes":model.code,
    };
    WS(ws);
    [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:DeleteType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
        [ws.dataArr removeObjectAtIndex:indexpath.row];
        [ws.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexpath.row inSection:indexpath.section]] withRowAnimation:UITableViewRowAnimationFade];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
- (void)stopButtonAction:(UIButton *)btn{
    CGPoint point = btn.center;//找到btn中心点记录下来
    point = [self.tableView convertPoint:point fromView:btn.superview];
    NSIndexPath* indexpath = [self.tableView indexPathForRowAtPoint:point];
    ObjectListIModel *model = self.dataArr[indexpath.row];
    if (model.isStop == 1) {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"" message:@"该项目已停用" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *updateAct = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           
        }];
        [alertC addAction:updateAct];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertC animated:YES completion:^{
            
        }];
        return;
    }
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderProject/stopProject",CJBaseUrl);
    NSDictionary *dicPar = @{@"code":model.code,
    };
    WS(ws);
    [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:DeleteType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
        model.isStop = 1;
        [ws.tableView reloadRow:indexpath.row inSection:0 withRowAnimation:(UITableViewRowAnimationFade)];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
- (void)xiugButtonAction:(UIButton *)btn{
    CGPoint point = btn.center;//找到btn中心点记录下来
    point = [self.tableView convertPoint:point fromView:btn.superview];
    NSIndexPath* indexpath = [self.tableView indexPathForRowAtPoint:point];
    ObjectListIModel *model = self.dataArr[indexpath.row];
    ZTXNewObjectLinesController * vc = [[ZTXNewObjectLinesController alloc] init];
    vc.isChangeStr = @"1";
    vc.projectName = model.projectName;
    vc.code = model.code;
    vc.strDownLoadCityCode  = model.shipperSubdivisionCode;
    vc.strGoodsNameCodes = model.coalType;
    vc.strGoodsNameName = model.coalTypeName;
    vc.strGoodsBigTypeCode = model.coalBigType;
    vc.strGoodsBigTypeName = model.coalBigTypeName;
    vc.strConsigneeLatitude = model.shipperLatitude;
    vc.strConsigneeLongitude = model.shipperLongitude;
    vc.shipperDetailAddress = model.shipperDetailAddress;
    vc.shipperAddress = model.shipperAddress;
    [self pushVc:vc];
}

- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, CJTableToTopHeight + kTopHeight + 5, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight -CJTableToTopHeight - 50 - SafeAreaBottomHeight - 5),UITableViewStylePlain)
            .tbDelegate(self)
            .tbDataSource(self)
            .tbSetOther(YES)
            .tbEstimatedRowHeight(YES)
            .tbMjHeadFooter(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {
            if (isheader) {
                [ws downRefresh];
            } else {
                [ws upRefresh];
            }
        };
    }
    [_tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    return _tableView;
}
- (UIButton *)comitterButton{
    if(!_comitterButton){
        self.comitterButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [self.comitterButton setFrame:CGRectMake(10, self.tableView.bottom + 10, SCREEN_WIDTH - 20, 50)];
        [self.comitterButton setTitle:@"新增项目" forState:(UIControlStateNormal)];
        [self.comitterButton addTarget:self action:@selector(comitterButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
        self.comitterButton.layer.masksToBounds = YES;
        self.comitterButton.layer.cornerRadius = 10;
        self.comitterButton.layer.borderWidth = 1;
        self.comitterButton.layer.borderColor = [UIColor cjMainColor].CGColor;
        [self.comitterButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        self.comitterButton.backgroundColor = [UIColor cjMainColor];
    }
    return _comitterButton;
}
-(UIView *)bgView{
    if (!_bgView) {
        self.bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        self.bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
        self.changeVoidceSet = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeVoidceSet:)];
        [self.bgView addGestureRecognizer:self.changeVoidceSet];
        [self.bgView addSubview:self.erwmView];
        [self.bgView addSubview:self.buttonImag];
    }
    return _bgView;
}
- (UIView *)erwmView{
    if (!_erwmView) {
        self.erwmView = [[UIView alloc] initWithFrame:CGRectMake(20, (SCREEN_HEIGHT - SCREEN_WIDTH - 40)/2, SCREEN_WIDTH - 40, SCREEN_WIDTH - 40)];
        
        [self.erwmView addSubview:self.titLabel];
        [self.erwmView addSubview:self.erwmImagView];
        self.erwmView.layer.masksToBounds = YES;
        self.erwmView.layer.cornerRadius = 20;
        self.erwmView.backgroundColor = [UIColor whiteColor];
    }
    return _erwmView;
}
- (UILabel *)titLabel{
    if(!_titLabel){
        self.titLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH - 50, 40)];
        self.titLabel.text = CJStringWithFormat(@"项目名称:");
        self.titLabel.font = [UIFont systemFontOfSize:14];
    }
    return _titLabel;
}

- (UIImageView *)erwmImagView{
    if (!_erwmImagView) {
        self.erwmImagView = [[UIImageView alloc] initWithFrame:CGRectMake(40 , 40, SCREEN_WIDTH - 120, SCREEN_WIDTH - 120)];
    }
    return _erwmImagView;
}
-(UIButton *)buttonImag{
    if (!_buttonImag) {
        self.buttonImag = [UIButton buttonWithType:(UIButtonTypeSystem)];
        [self.buttonImag setTitle:@"保存图片" forState:(UIControlStateNormal)];
        self.buttonImag.backgroundColor = CJRGBAColor(53, 170, 71, 1);
        [self.buttonImag setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        self.buttonImag.frame = CGRectMake(20,CGRectGetMaxY(self.erwmView.frame) + 10, SCREEN_WIDTH - 40, 44);
        self.buttonImag.layer.masksToBounds = YES;
        self.buttonImag.layer.cornerRadius = 22;
        [self.buttonImag addTarget:self action:@selector(buttonImagAction) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _buttonImag;
}

- (void)buttonImagAction{
    [self.bgView removeFromSuperview];
    //把view生成图片保存
    UIImageWriteToSavedPhotosAlbum([self convertViewToImage:self.erwmView], self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
{
    if (error) {
        [CJAlert showStringDismissWithDelay:@"保存失败"];
        [self.bgView removeFromSuperview];
    } else {
        [CJAlert showStringDismissWithDelay:@"保存成功"];
        [self.bgView removeFromSuperview];
    }
}

- (UIImage*)convertViewToImage:(UIView*)v{
    CGSize s = v.bounds.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
- (void)changeVoidceSet:(UITapGestureRecognizer *)sender{
    if(CGRectContainsPoint(self.erwmView.frame, [sender locationInView:self.bgView])){
        
    }else{
        [self.bgView removeFromSuperview];
    }
}
- (void)RightTextClick:(UIButton *)sender{
    LinesListController *sendVC = [[LinesListController alloc] init];
//    ObjectListIModel *model = self.dataArr[indexPath.row];
//    sendVC.projectName = model.projectName;
    [self pushVc:sendVC];
   
}
- (void)comitterButtonAction{
    ZTXNewObjectLinesController * vc = [[ZTXNewObjectLinesController alloc] init];
    vc.isChangeStr = @"0";
    [self pushVc:vc];
}
@end
